{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cpu\n",
      "cuda:0\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "\n",
    "# 创建一个 CPU 设备\n",
    "device_cpu = torch.device(\"cpu\")\n",
    "\n",
    "# 创建一个 CUDA 设备（如果有多个 GPU，可以通过索引指定）\n",
    "device_cuda = torch.device(\"cuda\")  # 默认 GPU，通常是第一个 GPU\n",
    "device_cuda_1 = torch.device(\"cuda:1\")  # 第二个 GPU\n",
    "\n",
    "# 将张量移动到指定设备\n",
    "tensor = torch.tensor([1.0, 2.0, 3.0])\n",
    "tensor_cpu = tensor.to(device_cpu)\n",
    "tensor_cuda = tensor.to(device_cuda)\n",
    "\n",
    "print(tensor_cpu.device)  # 输出: cpu\n",
    "print(tensor_cuda.device)  # 输出: cuda:0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "device(type='cuda')"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "device"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "假如变量a在cpu上，变量b在gpu 0上，现在要将两个变量相加，发现：**pytorch会自动将cpu设备上的变量转移到cuda上**\n",
    "\n",
    "但是不推荐这么做，因为：**把数据从cpu移到gpu是一件很慢的事情**，应尽量避免这种频繁的数据移动"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cpu\n",
      "cuda:0\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "tensor(32, device='cuda:0')"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = torch.tensor(12)\n",
    "print(a.device)\n",
    "\n",
    "b = torch.tensor(20).to(device_cuda)\n",
    "print(b.device)\n",
    "\n",
    "a + b"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
